﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace net根据匿名类生成实体类
{
    class Program
    {
        static void Main(string[] args)
        {

            var dagaJson =
                "{\"component_appid\":\"wx524df8de86b43de8\",\"authorizer_appid\":\"wxe482ed506b6bdc4c\",\"authorizer_refresh_token\":\"refreshtoken@@@Pub6-6HRDPTiDRpQyvD0NzDrb168uSL0wH0xLDMOa0s\"}";

            string ddds = GetPage("https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=IKjoFBoShCdHnRj8ioDYTqXYY71LGbyA9Elh0TYrDldGZ8Clfmjk0hVTUwB2YZI9OFzLTV-Lv2iPesfE3naVxsauNZxG8Mmnky2rli9Gf5AZTLeAGAMGY", dagaJson);

            //通过匿名对象生成实体类
            //var dynamicObj = new { id = 1, name = "小名",age=2 ,class1=new class1()};
            ////注意：只能是单个实体不能传入 List<T> ,集合需要   List[0]
            //string classCode = ClassGenerating.DynamicToClass(dynamicObj, "classDynamic");


            ////通过datatable生成实体类
            //DataTable dt = new DataTable();
            //dt.Columns.Add("Id", typeof(int));
            //dt.Columns.Add("Name");

            //classCode = ClassGenerating.DataTableToClass(dt, "classTatabale");


            ////通过sql语句生成实体类
            ////classCode = ClassGenerating.SqlToClass("select * from note", "Note", "127.0.0.1", "MyWork", "sa", "sasa");
            //classCode = ClassGenerating.SqlToClass("select * from dbo.AccessoriesDetail", "AccessoriesDetail", "NFDEntities");//通过 config connstring名称



            string dd = "{\"authorization_info\":{\"authorizer_appid\":\"wx2d71e0a1443eed78\",\"authorizer_access_token\":\"XTnoFusReeZfuAtf0X0qa938eDNN2YyuDWbPPWQ21Rv9QHUvUunW9sIzX8O4fiUAOqDPaFDBEQLULZyMql2HEf_nvQxgCg3Rb6mu6v316hWSHucQvM00QcQL-XhS8QmaRTZcAMDFHN\",\"expires_in\":7200,\"authorizer_refresh_token\":\"refreshtoken@@@QjQfqyhfQqalj4WB2jn38wRXzJaYTFJy13-aZekLOj8\",\"func_info\":[{\"funcscope_category\":{\"id\":1}},{\"funcscope_category\":{\"id\":2}},{\"funcscope_category\":{\"id\":3}},{\"funcscope_category\":{\"id\":4}},{\"funcscope_category\":{\"id\":5}},{\"funcscope_category\":{\"id\":6}},{\"funcscope_category\":{\"id\":7}},{\"funcscope_category\":{\"id\":8}},{\"funcscope_category\":{\"id\":11}},{\"funcscope_category\":{\"id\":12}},{\"funcscope_category\":{\"id\":13}},{\"funcscope_category\":{\"id\":10}}]}}";


            string dd2 = "{\"authorization_info\":{\"authorizer_appid\":\"wxf8b4f85f3a794e77\",\"authorizer_access_token\":\"QXjUqNqfYVH0yBE1iI_7vuN_9gQbpjfK7hYwJ3P7xOa88a89-Aga5x1NMYJyB8G2yKt1KCl0nPC3W9GJzw0Zzq_dBxc8pxIGUNi_bFes0qM\",\"expires_in\":7200,\"authorizer_refresh_token\":\"dTo-YCXPL4llX-u1W1pPpnp8Hgm4wpJtlR6iV0doKdY\",\"func_info\":[{\"funcscope_category\":{\"id\":1}},{\"funcscope_category\":{\"id\":2}}]}}";
            var t = JsonConvert.DeserializeObject<model>(dd2);

        }
        public static string GetPage(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/json";
                //request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }

        public static T Deserialize<T>(string jsonString)
        {
            const string pattern = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            var matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
            var reg = new Regex(pattern);
            jsonString = reg.Replace(jsonString, matchEvaluator);

            var ser = new DataContractJsonSerializer(typeof(T));
            byte[] buffer = Encoding.UTF8.GetBytes(jsonString);
            var stream = new MemoryStream(buffer) { Position = 0 };
            return (T)ser.ReadObject(stream);
        }
        /// <summary>
        /// 将时间字符串转为Json时间
        /// </summary>
        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
            return result;
        }

    }

    class class1
    {
        public int q { get; set; }
        public string w { get; set; }
    }
}
